import React, {
  FC,
  forwardRef,
  useCallback,
  useContext,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
} from 'react';
import { TextWidget, getMessage } from '@inbiz/react';
import cls from 'classnames';
import moment from 'moment';
import { GlobalRegistry } from '@inbiz/core';
import { AuthButton, hasAuth } from '@inbiz/basic/AuthForm';
import { InbizIcon } from '@inbiz/utils';
import {
  Button,
  Checkbox,
  Dropdown,
  Form,
  Input,
  Menu,
  MenuProps,
  message,
  Modal,
  Popconfirm,
  Progress,
  Radio,
  Space,
  Upload,
} from 'antd';
import { UploadFile } from 'antd/lib/upload/interface';
import { ButtonType } from 'antd/lib/button/button';
import FullModal from '../FullModal';
import { ActionConfigType, ActionProps, ActionsProps, DownloadTmplType } from '../../interfaces';
import tableApi from './serviceApi';
import { InBizTableCtx, InBizTableRefCtx, TableCtx } from '../../context';
import { ActionEnum, arrIsEmpty, EventsMap } from '../../shared';
import { useAppId, useColumnConfig, useExportFields, useIsDesigner } from '../../hooks';
import formatters from '../../formatters';
import '../../style.less';


const renderButton = (
  tableHeaderType: string = 'text',
  inLineType: string = 'text',
  position: string = 'tableHeader',
  text: string,
  icon?: { type: string; color: string },
) => {
  const renderMap = {
    text: () => getMessage(text),
    icon: () =>
      icon && icon?.type ? (
        <InbizIcon type={icon?.type} style={{ color: icon?.color }} />
      ) : (
        getMessage(text)
      ),
    iconText: () => (
      <span className="icon-text">
        {icon && icon?.type ? <InbizIcon type={icon?.type} style={{ color: icon?.color }} /> : null}
        {getMessage(text)}
      </span>
    ),
  };
  if (position === 'tableHeader') {
    return renderMap[tableHeaderType]();
  }
  return renderMap[inLineType]();
};

interface ImportActionProps {
  title?: string;
  // 按钮hover显示的title
  btnTitle?: string;
  showBtn?: boolean;
  buttonType?: ButtonType;
  buttonColor?:string;
  isDropAction?:boolean;
  actionType?: string;
  className?: string;
  operationflag?: string;
  showPageType?:string;
}

const DownLoad = () => {
  const { sourceModel } = useContext(InBizTableCtx);
  const fields = useExportFields();
  const appId = useAppId();
  const [loading, setLoading] = useState(false);
  const downLoadTmpl = useCallback(() => {
    setLoading(true);
    const param: DownloadTmplType = {
      fields,
      appId,
      sourceModel,
      importUpdate: true,
    };
    return tableApi
      .downloadTemplate(param)
      .catch((err) => {
        console.log('downloadTmpl-err', err.message);
      })
      .finally(() => setLoading(false));
  }, []);

  return (
    <div className="download-box">
      <TextWidget>Table.downloadTipsBefore</TextWidget>
      <Button type={'link'} loading={loading} onClick={downLoadTmpl}>
        <TextWidget>Table.importTemplate</TextWidget>
      </Button>
      <TextWidget>Table.downloadTipsAfter</TextWidget>
    </div>
  );
};

export const ImportAction = forwardRef((props: ImportActionProps, ref: any) => {
  const { buttonType,buttonColor,title, btnTitle, showBtn = true, className,showPageType } = props;
  const { tableCacheRef } = useContext(TableCtx);
  const isDesignable = useIsDesigner();
  const [form] = Form.useForm();
  const { emit, sourceModel } = useContext(InBizTableCtx);
  const fields = useExportFields();
  const appId = useAppId();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [file, setFile] = useState<UploadFile>();
  const [checkId, setCheckId] = useState(false);
  const [progress, setProgress] = useState<number>(0);
  const timerRef = useRef<any>();
  const clear = useCallback(() => {
    setProgress(0);
    setLoading(false);
  }, []);

  const onRemove = useCallback(() => {
    clear();
    return setFile(undefined);
  }, []);
  const beforeUpload = useCallback((val) => {
    setFile(val);
    clear();
    return false;
  }, []);

  const handleClose = useCallback(() => {
    setVisible(false);
    setCheckId(false);
    onRemove();
  }, []);

  const handleUpload = useCallback(() => {
    if (progress === 100) {
      clear();
      handleClose();
      return;
    }
    form
      .validateFields()
      .then(() => {
        if (!file) {
          return;
        }
        if (!file?.name?.endsWith('.xlsx') && !file?.name?.endsWith('.xls')) {
          form.setFields([
            {
              name: 'file',
              value: file.name,
              errors: [getMessage('Table.tips.uploadRestrictionPrompt')],
            },
          ]);
          return;
        }
        setLoading(true);
        const interval = 1000;
        const params = {
          file,
          fields,
          appId,
          sourceModel,
          importUpdate: checkId,
        };
        tableApi
          .importTable(params)
          .then((res: any) => {
            if (!res.IsSuccess) {
              message.error(res.Content);
              clear();
              return;
            }
            timerRef.current = setInterval(() => {
              tableApi
                .getProgress(res.Data)
                .then((fileRes: any) => {
                  if ([2, 3].includes(fileRes.Status)) {
                    message.error(getMessage('Table.tips.importFailure'));
                    clearInterval(timerRef.current);
                    clear();
                    return;
                  }
                  if (fileRes.Percent === 100) {
                    message.success(getMessage('Table.tips.import'));
                    clearInterval(timerRef.current);
                  }
                  return setProgress(fileRes.Percent);
                })
                .catch(() => {
                  clearInterval(timerRef.current);
                  return Promise.reject();
                });
            }, interval);
          })
          .catch((err: any) => {
            clear();
            console.log('importTable-err', err.message);
          });
      })
      .catch(() => {
        clear();
        clearInterval(timerRef.current);
      });
  }, [progress, file, checkId, timerRef, form]);
  const onClick = useCallback(() => {
    (emit as any)?.(EventsMap.onClick, props.actionType);
    if (!isDesignable) {
      setVisible(true);
    }
  }, []);
  const renderImportContent = useMemo(() => {
    return (
      <>
        {!progress ? (
          <>
            <DownLoad />
            <div className="select-file">
              <Form form={form} layout="inline">
                <Form.Item
                  name="file"
                  rules={[
                    {
                      required: true,
                      message: getMessage('Table.tips.pleaseSelectTheFile'),
                    },
                  ]}
                >
                  <Input readOnly />
                </Form.Item>
                <Upload
                  listType="text"
                  maxCount={1}
                  onRemove={onRemove}
                  beforeUpload={beforeUpload}
                  fileList={[]}
                >
                  <Button type="primary">
                    <TextWidget>Table.button.selectTheFile</TextWidget>
                  </Button>
                </Upload>
              </Form>
              <div className="import-update-data">
                <span style={{ marginRight: 16 }}>
                  <TextWidget>Table.isUpdate</TextWidget>
                </span>
                <Checkbox checked={checkId} onChange={(e) => setCheckId(e.target.checked)}>
                  <span style={{ color: 'red' }}>
                    <TextWidget>Table.importIdTips</TextWidget>
                  </span>
                </Checkbox>
              </div>
            </div>
          </>
        ) : (
          <>
            <div className="import-text">
              <TextWidget>Table.importing</TextWidget>：{file?.name}
            </div>
            <Progress percent={progress} />
          </>
        )}
      </>
    );
  }, [progress, checkId, form]);

  useEffect(() => {
    form.setFieldsValue({ file: file?.name });
  }, [file]);
  useEffect(() => {
    if (progress < 100) {
      return;
    }
    clear();
    setProgress(0);
    handleClose();
    clearInterval(timerRef.current);
    tableCacheRef?.current.refresh();
  }, [progress]);

  useImperativeHandle(
    ref,
    () => {
      return {
        showModal: (showModal: boolean) => {
          setVisible(showModal);
        },
      };
    },
    [],
  );

  return (
    <>
      {showBtn && (
        <Button
          type={buttonType?buttonType:buttonColor?'primary':''}
          className={className}
          operationflag={props.operationflag}
          title={btnTitle}
          onClick={onClick}
          style={{
            background:buttonColor?buttonColor:''
          }}
        >
          {title}
        </Button>
      )}
      <FullModal
        className="inbiz-import-modal"
        title={getMessage('Table.button.import')}
        width={500}
        okText={getMessage('Table.sure')}
        visible={visible}
        centered={true}
        okButtonProps={{ loading: loading }}
        onOk={handleUpload}
        onCancel={handleClose}
        forceRender
        destroyOnClose={true}
        render={renderImportContent}
      />
    </>
  );
});

export const ExportAction = forwardRef((props: ImportActionProps, ref: any) => {
  const { actionType,buttonColor, title, showBtn = true, className } = props;
  const { emit, sourceModel, rowSelection } = useContext(InBizTableCtx);
  const { searchRef, eventsRef } = useContext(InBizTableRefCtx);
  const {
    tableCacheRef,
    selectedRowKeys = [],
    cardsMap = [],
    conditions = {},
  } = useContext(TableCtx);
  const isDesignable = useIsDesigner();
  const appId = useAppId();
  let fields = useExportFields();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [exportType, setExportType] = useState<string>('allData');
  const [progress, setProgress] = useState(0);
  const fileRef = useRef<{ Data: string; Content: string }>();
  const timerRef = useRef();
  const isFilter = conditions?.condition?.some((item) => !!item.value) || false;
  const items: MenuProps['items'] = useMemo(() => {
    const items = [
      {
        label: getMessage('Table.button.allData'),
        key: 'allData',
      },
      {
        label: getMessage('Table.button.selectData'),
        key: 'selectData',
        disabled: !selectedRowKeys.length && !cardsMap?.size,
      },
      {
        label: getMessage('Table.button.filterData'),
        key: 'filterData',
        disabled: !isFilter,
      },
    ];
    if (!rowSelection) {
      items.splice(1, 1);
    }
    return items;
  }, [selectedRowKeys, cardsMap, rowSelection, conditions]);
  const initialValues = useMemo(() => {
    return {
      fileType: 0,
      checkId: false,
    };
  }, []);
  const handleMenuClick = useCallback(({ key }: { key: string }) => {
    (emit as any)?.(EventsMap.onClick, actionType);
    if (!isDesignable) {
      setVisible(true);
      setExportType(key);
    }
  }, []);
  const clear = useCallback(() => {
    setLoading(false);
    setProgress(0);
    fileRef.current = undefined;
  }, []);
  const onOk = useCallback(() => {
    if (isDesignable) {
      return;
    }
    setLoading(true);
    form
      .validateFields()
      .then(async (values) => {
        const { fileName, fileType, checkId } = values;
        if (!fileName) {
          return;
        }
        if (checkId && fields) {
          const hasId = fields.some((field) => field.proName === 'id');
          if (!hasId) {
            fields?.push({
              colName: undefined,
              proName: 'id',
            });
          }
        }
        const params = {
          fileName,
          fields,
          appId,
          sourceModel,
          importUpdate: checkId,
          fileType,
          recordIds: exportType == 'selectData' ? tableCacheRef?.current.keyList?.join() : '',
          conditions:
            exportType == 'filterData'
              ? formatters.filterCondition(searchRef?.current.conditions)
              : [],
          pageInfo: {},
          orderInfo: searchRef?.current.orders,
        };
        const fileData = await tableApi.exportTable(
          eventsRef?.current.onExportParamFormat?.(params) ?? params,
        );
        if (!fileData.IsSuccess) {
          message.error(fileData.Content);
          clear();
          return;
        }
        fileRef.current = fileData;
        (timerRef.current as any) = setInterval(() => {
          tableApi
            .getProgress(fileData.Data)
            .then((res) => {
              if ([2, 3].includes(res.Status)) {
                message.error(getMessage('Table.tips.exportFailure'));
                clear();
                return clearInterval(timerRef.current);
              }
              if (res.Percent === 100) {
                clearInterval(timerRef.current);
              }
              return setProgress(res.Percent);
            })
            .catch(() => {
              clearInterval(timerRef.current);
              return Promise.reject();
            });
        }, 1000);
      })
      .catch(() => clear());
  }, [exportType, form]);

  const onCancel = useCallback(() => {
    setVisible(false);
    form.resetFields();
  }, [form]);
  const renderExportContent = useMemo(() => {
    return (
      <div className="inbiz-export">
        <Form form={form} hideRequiredMark={true} initialValues={initialValues} labelAlign="left">
          <Form.Item name="fileType" label={getMessage('Table.exportType')} colon={false}>
            <Radio.Group>
              <Radio value={0}>Excel</Radio>
              <Radio value={1}>PDF</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="fileName"
            label={getMessage('Table.exportFileName')}
            colon={false}
            rules={[
              {
                required: true,
                message: getMessage('Table.tips.pleaseEnterTheExportFileName'),
              },
            ]}
          >
            <Input allowClear />
          </Form.Item>
          <Form.Item
            name="checkId"
            valuePropName="checked"
            label={getMessage('Table.exportId')}
            colon={false}
          >
            <Checkbox>
              <span style={{ color: 'red' }}>
                <TextWidget>Table.exportIdTips</TextWidget>
              </span>
            </Checkbox>
          </Form.Item>
        </Form>
      </div>
    );
  }, [form]);
  useEffect(() => {
    if (!visible) return;
    form.setFieldValue('fileName', `${moment().format('YYYYMMDDHHmmss')}`);
  }, [visible]);
  useEffect(() => {
    if (progress < 100 || !fileRef.current) {
      return;
    }
    tableApi
      .getFile(fileRef.current.Content, fileRef.current.Data)
      .then(() => {
        message.success(getMessage('Table.tips.export'));
        setVisible(false);
        form.resetFields();
      })
      .finally(() => {
        clear();
        clearInterval(timerRef.current);
      });
  }, [progress]);

  useImperativeHandle(
    ref,
    () => {
      return {
        showModal: (showModal: boolean) => {
          setVisible(showModal);
        },
      };
    },
    [],
  );
  return (
    <>
      {showBtn && (
        <Dropdown className={className} overlay={<Menu items={items} onClick={handleMenuClick} />}>
          <Button type={buttonColor?'primary':''} style={{background:buttonColor?buttonColor:''}}>
            <Space size={5}>
              {title}
              <InbizIcon type="icon-ic-arrow-down-bold" style={{ lineHeight: 0 }} />
            </Space>
          </Button>
        </Dropdown>
      )}
      <FullModal
        className="inbiz-export-modal"
        title={getMessage('Table.button.export')}
        width={500}
        okText={getMessage('Table.sure')}
        visible={visible}
        centered={true}
        okButtonProps={{ loading }}
        onOk={onOk}
        forceRender={true}
        onCancel={onCancel}
        render={renderExportContent}
      />
    </>
  );
});

const Action = React.memo((props: ActionProps) => {
  const { buttonType,buttonColor,isDropAction, className, position, icon, ...other } = props;
  const { formItems, thumbFormItems } = useColumnConfig();
  const title = renderButton(
    formItems.tableHeaderBtnShow,
    formItems.inLineBtnShow,
    position,
    props.actionName,
    icon,
  );
  const btnTitle = useMemo(() => {
    if (position === 'tableHeader') {
      return formItems.tableHeaderBtnShow == 'icon' ? getMessage(props.actionName) : ''
    }
    return formItems.inLineBtnShow == 'icon' ? getMessage(props.actionName) : '';
  }, [])
  const [loading, $loading] = useState(false);
  const { state, dispatch, emit, tableCacheRef } = useContext(TableCtx);
  const { eventsRef, searchRef } = useContext(InBizTableRefCtx);
  const { tableViewType, showPageType, primarykey } = useContext(InBizTableCtx);
  const [disabled, setDisabled] = useState(() => other.disabled ?? false);
  const isQueryActive = props.actionType == ActionEnum.query && searchRef.current.isQueryClick && searchRef.current.conditions?.length;
  const interRef = useRef<any>()
  const onClick = useCallback(
    async (e) => {
      if (props.actionType == 'save' || props.actionType == 'saveAndNew') {
        $loading(true)
      }
      document.body.click();
      const nope = () =>
        new Promise((resolve) => {
          setTimeout(() => {
            resolve(undefined);
          }, 0);
        });
      await nope();
      e && e.stopPropagation();
      if (props.actionType !== ActionEnum.del) {
        (emit as any)?.(EventsMap.onClick, props.actionType, props);
      }
      await dispatch?.({ ...props });
      if (props.actionType == 'saveAndNew' || props.actionType == 'save') {
        interRef.current = setTimeout(() => {
          $loading(false)
        }, props.actionType == 'saveAndNew' ? 500 : 1000);
      }
    },
    [props.actionType],
  );
  useEffect(() => {
    return () => {
      clearTimeout(interRef.current)
    }
  }, [])
  const onCancel = (e: any) => {
    e && e.stopPropagation();
  };
  const isShowModal = useMemo(() => {
    return position === 'tableHeader' || tableViewType === 'card' || showPageType == 'thumbnail';
  }, []);

  useEffect(() => {
    const preNext = [ActionEnum.pre, ActionEnum.next];
    if (state) {
      state.then((res: { data: { [key: string]: any } }) => {
        const tableData = tableCacheRef.current?.data ?? [];
        const { data = {} } = res || {};
        let currentData = {}
        if (Object.keys(data).length) {
          tableCacheRef.current = {
            ...tableCacheRef.current,
            currentData: data
          };
        }
        currentData = Object.keys(data).length ? data : tableCacheRef.current.currentData;
        if (preNext.includes(props.actionType)) {
          const curInx = tableData.findIndex((row: { [key: string]: any }) => row?.[primarykey] == currentData?.[primarykey]);
          const isPre = props.actionType == ActionEnum.pre;
          const isDisabled = tableData[isPre ? curInx - 1 : curInx + 1] ? false : true;
          setDisabled(isDisabled);
        }
      })
      state.finally(() => {
        if (!other.disabled && !preNext.includes(props.actionType)) {
          setDisabled(false);
        }
      });
    }
  }, []);
  const colorConfig=useMemo(()=>{
    let styleConfig={}
      if(buttonColor){
        if(position=='inline'){
          styleConfig.color=buttonColor
        }else{
         styleConfig.background=buttonColor
        }
      }else{
        if(position=='inline'){
          styleConfig.color='var(--inbiz-color-primary)'
          if(showPageType=='thumbnail'){
            if(thumbFormItems.selected=='default3'){
              if(!isDropAction){
                styleConfig.color='#fff'
              }
            }
          }
        }
      }
      return styleConfig
    },[buttonColor])
  const renderDelBtn = useMemo(() => {
    return (
      <Button
        operationflag={props.operationflag}
        className={className}
        type={buttonColor?position=='inline'?buttonType:"primary":buttonType}
        style={colorConfig}
        title={btnTitle}
        disabled={disabled}
        onClick={async (e) => {
          e.stopPropagation();
          const primaryKey = tableCacheRef?.current?.primaryKey || 'id';
          (emit as any)?.(EventsMap.onClick, props.actionType, props);
          if (props.actionType !== ActionEnum.del) {
            const result =
              (await eventsRef?.current.onBeforeOperationAsync?.(props.actionType, props?.data)) ??
              true;
            if (!result) {
              return;
            }
          }
          if (!props.data?.[primaryKey] && arrIsEmpty(tableCacheRef.current.keyList)) {
            message.warning(getMessage('Table.tips.pleaseSelectTheDataToBeDeleted'));
            return;
          }
          if (isShowModal) {
            Modal.confirm({
              title: getMessage('Table.tips.confirmDelete'),
              okText: getMessage('Table.sure'),
              cancelText: getMessage('Table.cancel'),
              onOk() {
                onClick(e);
              },
            });
          }
        }}
      >
        {title}
      </Button>
    );
  }, []);
  const renderDel = useMemo(() => {
    return tableViewType !== 'card' ? (
      <Popconfirm
        title={getMessage('Table.tips.confirmDelete')}
        placement="bottom"
        onConfirm={(e) => {
          e.stopPropagation();
          onClick(e);
        }}
        onCancel={onCancel}
        okText={getMessage('Table.sure')}
        cancelText={getMessage('Table.cancel')}
        disabled={isShowModal || disabled}
      >
        {renderDelBtn}
      </Popconfirm>
    ) : (
      renderDelBtn
    );
  }, []);
  const actionMap = {
    del: (() => {
      return renderDel;
    })(),
    thoroughDel: (() => {
      return renderDel;
    })(),
    import: <ImportAction title={title} btnTitle={btnTitle} {...props} />,
    export: <ExportAction title={title} btnTitle={btnTitle} {...props} />,
  };
  const Comp = useMemo(() => actionMap[props.actionType], [props.actionType]);

  return Comp ? (
    Comp
  ) : (
    <>
      <Button
        className={className}
        disabled={disabled}
        operationflag={props.operationflag}
        type={buttonColor?(position!='inline')?'primary':buttonType:buttonType}
        title={btnTitle}
        onClick={onClick}
        style={
          colorConfig
        }
        loading={loading}
      >
        {title}
        {isQueryActive ? <div className='query-mark'></div> : null}
      </Button>
    </>
  );
});
Action.displayName = 'Action';

export const DropDownActions: React.FC<ActionsProps & {
  setDropDownBtn: React.Dispatch<React.SetStateAction<never[]>>
  setHideActions: React.Dispatch<React.SetStateAction<boolean>>
}> = (props) => {
  const { className, actions = [], leftAuthActions = [], authActions = [], isTableActions, index = 0, setDropDownBtn, setHideActions, ...other } = props;
  const [leftBtn, setLeftBtn] = useState<ActionConfigType[]>([]);
  const { formItems } = useColumnConfig();
  const { tableRef } = useContext(TableCtx);
  const { showSortIcon } = useContext(InBizTableCtx);
  const getDropDownBtns = (value: boolean) => {
    if (!value) return;
    if (!isTableActions) {
      setLeftBtn(actions);
      return;
    }
    const list: any = tableRef.current.querySelectorAll(
      '.ant-table-cell.actions.inbiz-table-cell .inbiz-actions',
    );
    if (list?.length) {
      const btns = [...list][index]?.querySelectorAll('button');
      const actionColumn = tableRef.current.querySelector('.ant-table-cell.actions.inbiz-table-cell')
      const actionColumnWidth = formItems?.actionColumnWidth || 0;
      const actionColumnPLeft = parseFloat(getComputedStyle(actionColumn).paddingLeft || '0');
      const actionColumnPRight = parseFloat(getComputedStyle(actionColumn).paddingRight || '0');
      const _actionColumnWidth = actionColumnWidth - actionColumnPLeft - actionColumnPRight;
      const cache: ActionConfigType[] = [];
      const _authActions = [...authActions];
      if (btns?.length) {
        let elTotalWidth = 16; // 16像素为更多按钮的宽度
        [...btns]?.forEach((el) => {
          const actionName = el.innerText || el.title;
          const elWidth = el.offsetWidth || 0;
          const elMarginLeft = parseFloat(getComputedStyle(el).marginLeft || '0');
          const elMarginRight = parseFloat(getComputedStyle(el).marginRight || '0');
          const totalWidth = elWidth + elMarginLeft + elMarginRight;
          elTotalWidth += totalWidth;
          if (elTotalWidth > _actionColumnWidth) {
            const index = _authActions.findIndex((item) => getMessage(item.actionName) === actionName);
            if (index !== -1) {
              cache.push(_authActions[index]);
              _authActions.splice(index, 1);
            }
          }
        });
      }
      setDropDownBtn(cache);
      setLeftBtn(cache);
    }
    setHideActions(false);
  };
  const items = leftBtn?.map((action) => {
    return {
      key: action.id,
      label: <Action {...other} {...action} data={props.data} buttonType={'text'} isDropAction = {true} />,
    };
  });
  useEffect(() => {
    setTimeout(() => {
      getDropDownBtns(true);
    }, 200)
  }, [index, GlobalRegistry.getDesignerLanguage()]);
  return items.length ? (
    <Dropdown
      overlayClassName={'inbiz-table-dropdown-overlay-menu'}
      overlay={<Menu items={items} />}
      onVisibleChange={getDropDownBtns}
      placement={showSortIcon ? 'bottom' : 'bottomLeft'}
    >
      {props.children}
    </Dropdown>
  ) : null;
};

const Actions: FC<ActionsProps> = (props) => {
  const { auth, inbiz } = useColumnConfig();
  const { className, style, actions = [], displayQty = 3, isTableActions = false, topBtnMorePopover, buttonPosition, ...other } = props;
  const [ dropDownBtn, setDropDownBtn] = useState([]);
  const [ hideActions, setHideActions ] = useState(isTableActions);
  const newActions = actions?.map((ele) => {
    return {
      ...ele,
      ...hasAuth(
        {
          table: [{ ...ele, operationType: ele.actionType }],
          auth: auth,
        },
        ele.actionType,
        inbiz?.auth,
      ),
    };
  });
  // 下拉按钮集合
  const leftActions = newActions?.slice(displayQty);
  // 下拉权限按钮集合
  const leftAuthActions = leftActions?.filter((ele) => ele.auth);
  // 过滤出所有权限按钮
  const authActions = newActions?.filter((ele) => ele.auth);
  const moreActions = useMemo(() => {
    return (
      <DropDownActions
        {...props}
        actions={leftAuthActions}
        authActions={authActions}
        setDropDownBtn={setDropDownBtn}
        setHideActions={setHideActions}
      >
        <Button
          icon={<InbizIcon type="icon-more1" />}
          style={{ width: 16,color:'var(--inbiz-color-primary)' }}
          className="action-btn-more"
        />
      </DropDownActions>
    );
  }, [authActions]);
  return (
    <div 
      className={cls('inbiz-actions', className, {'hide-first': actions.length == dropDownBtn.length }, { 'hide-actions':  hideActions})}
      style={style}
    >
      {actions?.slice(0, displayQty).map((action, index) => {
        const { render, ...rest } = action;
        if (render) {
          return render?.('action-item');
        }

        return (
          <AuthButton
            auth={auth}
            operation={[{ ...action, operationType: action.actionType }]}
            type={action.actionType}
            authList={inbiz?.auth}
            key={index}
          >
            <>
              <Action
                key={action.id}
                {...other}
                {...rest}
                data={props.data}
                className={'action-item'}
              />
              {
                !isTableActions && topBtnMorePopover && 
                <ToolbarMoveBtn {...props}  actions={actions} authList={inbiz?.auth} auth={auth}   />
              }
            </>
          </AuthButton>
        );
      })}
      {(((actions?.length || 0) > displayQty && leftAuthActions && leftAuthActions.length > 0) ||
        isTableActions) &&
        moreActions}
      {
        topBtnMorePopover && buttonPosition === 'right' && !isTableActions && !!actions?.length && <i style={{marginLeft: -42 }}></i>
      }
    </div>
  );
};

// 顶部更多按钮
function ToolbarMoveBtn ({actions, authList, auth, ...other}: { actions: ActionConfigType[], authList: AuthListItem[], auth: string}) {
  const [showNumber, $showNumber] = useState(0);
  const toolbarMoveBoxRef = useRef<HTMLDivElement>(null)
  // 有权限的按钮
  const actionBtns = useMemo(() => {
    return actions.filter(item => {
      const operationFlagList = (authList || []).find(
        (ele) => ele.GroupOutId === auth && ele.Button === item?.operationflag,
      );
      return authList?.length === 0 || !operationFlagList
        ? true
        : operationFlagList?.IsHavePerm;
    })
  }, [actions, authList, auth]);

  const items = useMemo(() => {
    return actionBtns.slice(showNumber)?.map((action) => {
      return {
        key: action.id + action?.disabled || '',
        label: <Action {...other}  {...action} buttonType={'text'} />,
      };
    })
  }, [actionBtns, showNumber]);
  return <div className='toolbarMoveBtnBox'  ref={toolbarMoveBoxRef}>
  <Dropdown
    overlayClassName={'inbiz-table-dropdown-overlay-menu'}
    overlay={<Menu items={items} />}
    onVisibleChange={(visible) => {
      if (visible) {
        // 计算更多中显示几个按钮
        let y: number, number = 0;
        toolbarMoveBoxRef.current?.parentElement?.parentElement?.querySelectorAll('.inbiz-actions > .ant-btn').forEach((item, index) => {
          if (!number) {
            const clientRect = item.getBoundingClientRect();
            if (index === 0) {
              y = clientRect.y;
            } else {
              if ((clientRect.y - y) > 10) {
                number = index;
                $showNumber(number)
              }
            }
          }
        })
      }
    }}
  >
    <Button
      icon={<InbizIcon type="icon-more1" />}
      className="action-item"
    />
  </Dropdown>
</div>
}
export default React.memo(Actions);
